import logging
from locust import FastHttpUser, task, between
import csv
import random

from encrypt import encryptAES

# 配置日志（INFO级别，输出到控制台和文件）
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("locust_test.log"),  # 输出到文件
        logging.StreamHandler()  # 输出到控制台
    ]
)
logger = logging.getLogger("locust")


class SolUser(FastHttpUser):
    wait_time = between(0.1, 0.5)
    users = []
    login_failed = False

    def __init__(self, environment):
        super().__init__(environment)
        self.credentials = None
        self.getProductDetails_data = None

    def on_start(self):
        if not SolUser.users:
            try:
                logging.error("获取用户帐号文件，开始------")
                with open("token_gao.csv", "r") as f:
                    SolUser.users = list(csv.DictReader(f))
                self.getProductDetails_data = encryptAES({
                    "id": 800107098,
                })
            except Exception as e:
                logging.error(e)
                logging.error("获取用户帐号文件失败，终止------")
                exit(-1)
        # 随机选择账号
        self.credentials = random.choice(self.users)

    @task
    def step5_listAnchorGoods(self):
        data = {
            "id": 800107098,
        }
        resp = self.client.post("https://slbapi.sootoken.com.cn/api/newProduct/getProductDetails",
                                json=data,
                                headers={
                                    "Authorization": self.credentials["token"],
                                    "Content-Type": "application/json",
                                    "x-signature": self.getProductDetails_data
                                })
        logging.info(resp.json())
